/*
 * Copyright 2016 Yan Zhenjie
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mingmen.canting.caigourenyuan;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.mingmen.canting.R;
import com.mingmen.canting.adapter.ImagePickerAdapter;
import com.mingmen.canting.adapter.ImagePickerNewAdapter;
import com.mingmen.canting.base.BaseBean;
import com.mingmen.canting.chushizhang.JingLiCompareActivity;
import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.httpconfig.HttpResponse;
import com.mingmen.canting.imageloader.GlideImageLoader;
import com.mingmen.canting.immersionbar.ImmersionBar;
import com.mingmen.canting.model.PicSendModel;
import com.mingmen.canting.util.GsonUtil;
import com.mingmen.canting.util.MyStringUtils;
import com.mingmen.canting.util.SharePreferenceUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;


/**
 * <p>
 * ListView形式的侧滑菜单，支持横向和竖向的。
 * </p>
 * Created by Yan Zhenjie on 2016/7/27.
 */
public class JuBaoActivity extends Activity implements ImagePickerNewAdapter.OnRecyclerViewItemClickListener {


    @BindView(R.id.layout_close)
    LinearLayout layout_close;
    @BindView(R.id.img_return)
    ImageView img_return;


    ArrayList<ImageItem> images = null;

    private ImagePicker imagePicker;

    GridLayoutManager gridLayoutManager1;
    @BindView(R.id.layout_pic)
    RecyclerView layout_pic;
    private ImagePickerNewAdapter adapter;
    private ArrayList<ImageItem> selImageList = new ArrayList<>(); //当前选择的所有图片
    //    private int maxImgCount = 8;               //允许选择图片最大数
    private int maxImgCount = 3;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;

    @BindView(R.id.layout_jubaoleixing)
    LinearLayout layout_jubaoleixing;
    private int resurtResurant = 100;
    @BindView(R.id.text_type)
    TextView text_type;
    @BindView(R.id.btn_jubao)
    Button btn_jubao;
    @BindView(R.id.edit_reason)
    EditText edit_reason;

    String token;
    String codeId;
    String codeName;
    String supplierId;
    List<File> myfile = new ArrayList<>();
    List<String> pictureList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jubao);
        ButterKnife.bind(this);
        createPicker();
        token = (String) SharePreferenceUtil.get(this, "token", "");
        supplierId = (String) SharePreferenceUtil.get(JuBaoActivity.this,"supplierId","");
        gridLayoutManager1 = new GridLayoutManager(this, 3);
        layout_pic.setLayoutManager(gridLayoutManager1);
        adapter = new ImagePickerNewAdapter(this, selImageList, maxImgCount);
        adapter.setOnItemClickListener(this);

        layout_pic.setLayoutManager(new GridLayoutManager(this, 3));
        layout_pic.setHasFixedSize(true);
        layout_pic.setAdapter(adapter);
    }


    @OnClick({R.id.layout_close, R.id.img_return, R.id.layout_jubaoleixing, R.id.btn_jubao})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.img_return:
            case R.id.layout_close:
                finish();
                break;
            case R.id.layout_jubaoleixing:
//                startActivity(new Intent(JuBaoActivity.this, JuBaoShangJiaActivity.class));
                intent = new Intent(JuBaoActivity.this, JuBaoShangJiaActivity.class);
                intent.putExtra("flag", "1");
                startActivityForResult(intent, resurtResurant);
                break;
            case R.id.btn_jubao:
                if (TextUtils.isEmpty(codeId)) {
                    Toast.makeText(this, "请选择举报类型", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(edit_reason.getText().toString())) {
                    Toast.makeText(this, "请输入举报原因", Toast.LENGTH_SHORT).show();
                } else {
//                    codeId = data.getStringExtra("codeId");
//                    codeName
                    String photos = MyStringUtils.returnStringBuffer(pictureList);
                    Log.d("Photos", photos);

                    HttpResponse.setSupplierAccusation(token, supplierId, photos, edit_reason.getText().toString(), codeId, new StringCallback(this) {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            BaseBean baseBean = new BaseBean();
                            baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                            if (baseBean.getCode() == 0) {
                                finish();
                            }
                            Toast.makeText(JuBaoActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                break;
        }
    }

    File file;


    @Override
    public void onItemClick(View view, int position) {

        switch (view.getId()) {
            case R.id.img_cel:
                selImageList.remove(position);
                adapter.setImages(selImageList);
                adapter.notifyDataSetChanged();
                break;
            case R.id.iv_img:
                switch (position) {
                    case IMAGE_ITEM_ADD:
                        ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                        Intent intent1 = new Intent(JuBaoActivity.this, ImageGridActivity.class);

//                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                        startActivityForResult(intent1, REQUEST_CODE_SELECT);
                        break;
                    default:
                        //打开预览
                        Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                        intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                        intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                        intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                        startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                        break;
                }

                break;

        }
    }

    String path;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
                for (int i = 0; i < images.size(); i++) {
                    Log.d("dkdkdkk", images.get(i).path);
                    path = images.get(i).path;
                    file = new File(path);
                    myfile.add(file);
                }
                HttpResponse.pictureSend("123", myfile, new StringCallback(JuBaoActivity.this) {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.d("DKkdkdkd", s);
                        PicSendModel picSendModel = new PicSendModel();
                        picSendModel = GsonUtil.GsonToBean(s, PicSendModel.class);
                        pictureList = picSendModel.getData();
                        myfile.clear();
                        images.clear();
                    }
                });
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
                for (int i = 0; i < images.size(); i++) {
                    Log.d("dkdkdkk", images.get(i).path);
                    path = images.get(i).path;
                    file = new File(path);
                    myfile.add(file);
                }
                HttpResponse.pictureSend("123", myfile, new StringCallback(JuBaoActivity.this) {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.d("DKkdkdkd", s);
                        PicSendModel picSendModel = new PicSendModel();
                        picSendModel = GsonUtil.GsonToBean(s, PicSendModel.class);
                        pictureList = picSendModel.getData();

                        myfile.clear();
                        images.clear();
                    }
                });
            }
        } else if (resultCode == resurtResurant) {
            codeId = data.getStringExtra("codeId");
            codeName = data.getStringExtra("codeName");
            text_type.setText(codeName);
        }

    }

    public void createPicker() {
        imagePicker = ImagePicker.getInstance();

        imagePicker.setImageLoader(new GlideImageLoader());
        imagePicker.setMultiMode(true);
        imagePicker.setShowCamera(true);
        imagePicker.setCrop(false);
        imagePicker.setSaveRectangle(true);
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);
        Integer width = Integer.valueOf(280);
        Integer height = Integer.valueOf(280);
        width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, width, getResources().getDisplayMetrics());
        height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, height, getResources().getDisplayMetrics());
        imagePicker.setFocusWidth(width);
        imagePicker.setFocusHeight(height);
        imagePicker.setOutPutX(Integer.valueOf(800));
        imagePicker.setOutPutY(Integer.valueOf(800));
    }
}